import base64
from odoo.fields import Binary, Field

from ..functions.aliyun_oss_bucket import AliyunOSSBucket

Binary.filename = None  # 文件名


class Binary(Field):

    # 修改read方法,当对应附件中存储有数据时取附件的数据，没有的话取附件中的url
    def read(self, records):
        assert self.attachment
        domain = [
            ('res_model', '=', records._name),
            ('res_field', '=', self.name),
            ('res_id', 'in', records.ids),
        ]
        data = {}

        for att in records.env['ir.attachment'].sudo().search(domain):

            if not att.url:
                data[att.res_id] = att.datas
            if not AliyunOSSBucket(records.env).get_oss_aliyun_enabled():  # 检测配置
                data[att.res_id] = att.datas
            if not AliyunOSSBucket(records.env).get_oss_aliyun_connected():  # 检测连接
                data[att.res_id] = att.datas
            else:
                # 创建oss对象
                bucket = AliyunOSSBucket(records.env).get_aliyun_oss_bucket()
                if bucket:
                    try:
                        datas = base64.encodebytes(bucket.get_object_with_url(att.url).read())
                        data[att.res_id] = datas
                    except:
                        data[att.res_id] = att.datas
                else:
                    data[att.res_id] = att.datas

        records.env.cache.insert_missing(records, self, map(data.get, records._ids))

    Binary.read = read
